import os
import shutil
from fastapi import UploadFile
from ..config import VIDEO_DIR
import aiofiles
import logging

logger = logging.getLogger(__name__)

__all__ = [
    'save_upload_file',
    'save_file_chunk',
    'merge_chunks',
    'delete_file',
    'get_file_size',
    'create_temp_upload_dir'
]

async def save_upload_file(upload_file: UploadFile, filename: str) -> str:
    """保存上传的文件"""
    try:
        file_path = os.path.join(VIDEO_DIR, filename)
        
        # 异步写入文件
        async with aiofiles.open(file_path, 'wb') as out_file:
            content = await upload_file.read()
            await out_file.write(content)
            
        return file_path
    except Exception as e:
        logger.error(f"Error saving file: {str(e)}")
        raise

async def save_file_chunk(chunk: bytes, filename: str, chunk_number: int) -> str:
    """保存文件分片"""
    try:
        temp_dir = os.path.join(VIDEO_DIR, f"temp_{filename}")
        os.makedirs(temp_dir, exist_ok=True)
        chunk_path = os.path.join(temp_dir, f"chunk_{chunk_number}")
        
        async with aiofiles.open(chunk_path, 'wb') as out_file:
            await out_file.write(chunk)
            
        return chunk_path
    except Exception as e:
        logger.error(f"Error saving chunk: {str(e)}")
        raise

async def merge_chunks(filename: str, total_chunks: int) -> str:
    """合并文件分片"""
    try:
        temp_dir = os.path.join(VIDEO_DIR, f"temp_{filename}")
        final_path = os.path.join(VIDEO_DIR, filename)
        
        async with aiofiles.open(final_path, 'wb') as outfile:
            for i in range(total_chunks):
                chunk_path = os.path.join(temp_dir, f"chunk_{i}")
                async with aiofiles.open(chunk_path, 'rb') as chunk:
                    content = await chunk.read()
                    await outfile.write(content)
        
        # 清理临时文件夹
        shutil.rmtree(temp_dir)
        return final_path
    except Exception as e:
        logger.error(f"Error merging chunks: {str(e)}")
        raise

def delete_file(file_path: str) -> None:
    """删除文件"""
    try:
        if os.path.exists(file_path):
            os.remove(file_path)
    except Exception as e:
        logger.error(f"Error deleting file: {str(e)}")
        raise

def get_file_size(file_path: str) -> int:
    """获取文件大小"""
    try:
        return os.path.getsize(file_path)
    except Exception as e:
        logger.error(f"Error getting file size: {str(e)}")
        raise

def create_temp_upload_dir(upload_id: str) -> str:
    """创建临时上传目录"""
    temp_dir = os.path.join(VIDEO_DIR, f"temp_{upload_id}")
    os.makedirs(temp_dir, exist_ok=True)
    return temp_dir 